<template>
    <a-form class="search-form" v-if="searchLoaded">
        <a-row :gutter="[16, 0]">
            <template v-for="item in options.column" :key="item.key">
                <a-col v-if="item.search && item.key !== 'action'" :span="item.span || 6">
                    <a-form-item :label="item.title" v-bind="useFormObj.validateInfos[item.key]">
                        <!-- <slot name="slot_table_header_seach"></slot> -->
                        <template v-if='!item.searchSlot'>
                            <a-input
                                v-if="item.type === 'text' || !item.type"
                                v-model:value.trim="modelRef[item.key]"
                                :maxlength="item.maxlength || 40"
                                :placeholder="item.searchPlaceholder || item.placeholder || '请输入'"
                            ></a-input>
<!--                            v-model:searchValue="item.searchFilterValue"-->
                            <a-tree-select
                                v-if="item.type === 'treeSelect'"
                                v-model:value="modelRef[item.key]"
                                :fieldNames="item.fieldNames"
                                style="width: 100%"
                                v-model:treeExpandedKeys="item.SearchExpandedRowKeys"
                                :dropdownMatchSelectWidth="false"
                                :tree-checkable="item.treeCheckable || false"
                                :filterTreeNode="item.filterTreeNode || false"
                                @search="item.searchFetch"
                                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                :tree-data="item.dicData"
                                :placeholder="item.searchPlaceholder || item.placeholder || '请输入'"
                                :load-data="item.onLoadData"
                                :maxTagCount="item.maxTagCount || 1"
                                allow-clear
                                :showArrow="true"
                                :showSearch="item.showSearch || false"
                                :show-checked-strategy="item.showCheckedStrategy"
                            >
                                <template #title="scope">
                                <span
                                    v-if="scope.contextId"
                                    class="loading-more-style"
                                    @click.stop="item.loadingMore(scope)"
                                >
                                    {{ scope[item.fieldNames.label] }}
                                    <i class="icon-zhankai"></i>
                                </span>
                                    <template v-else>{{ scope[item.fieldNames.label] }}</template>
                                </template>
                            </a-tree-select>
                            <a-range-picker
                                v-if="item.type === 'rangePicker'"
                                v-model:value="modelRef[item.key]"
                                :disabled-date="current => disabledDateCompute(item.disabledDate, current, item.disabledDays)"
                                :disabled-time="item.disabledRangeTime"
                                @openChange="onOpenChange"
                                @calendarChange="onCalendarChange"
                                @ok="onOk"
                                :show-time="{
                                    hideDisabledOptions: true,
                                    defaultValue: [
                                        dayjs('00:00:00', 'HH:mm:ss'),
                                        dayjs('11:59:59', 'HH:mm:ss')
                                    ]
                                }"
                                :valueFormat="item.valueFormat || 'x'"
                                format="YYYY-MM-DD HH:mm:ss"
                                style="width: 100%"
                            />
                            <a-cascader
                                v-if="item.type === 'cascader'"
                                v-model:value="modelRef[item.key]"
                                style="width: 100%"
                                type="cascader"
                                :multiple="item.multiple"
                                max-tag-count="responsive"
                                :options="item.dicData"
                                :placeholder="item.searchPlaceholder || item.placeholder || '请输入'"
                            ></a-cascader>

                            <a-select
                                v-if="item.type === 'select'"
                                v-model:value="modelRef[item.key]"
                                :search-value="item.searchFilterValue"
                                :mode="item.mode"
                                :fieldNames="item.fieldNames"
                                :showArrow="true"
                                :show-search="item.showSearch"
                                :filter-option="item.filterOption"
                                style="width: 100%"
                                :allowClear="true"
                                @search="item.searchFetch"
                                @input='item.handleInput'
                                :max-tag-count="item.maxTagCount"
                                :placeholder="item.searchPlaceholder || item.placeholder || '请输入'"
                                :options="item.dicData"
                            ></a-select>
                        </template>
                        <slot v-if='item.searchSlot' :name="`${item.key}Search`"></slot>
                    </a-form-item>
                </a-col>
            </template>
            <a-col :span="6">
                <a-form-item>
                    <a-space size="middle">
                        <a-button
                            v-if="options.column.some((item: any) => item.search)"
                            type="primary"
                            @click="searchChange"
                        >
                            搜索
                        </a-button>
                        <a-button
                            v-if="options.column.some((item: any) => item.search)"
                            @click="searchReset"
                        >
                            重置
                        </a-button>
                        <a-button
                            v-if="options.addBtn && options.permissions?.add"
                            type="primary"
                            @click="toAdd"
                        >
                            新增
                        </a-button>
                        <a-button
                            v-if="options.allDelBtn && options.permissions?.del"
                            type="primary"
                            @click="toAllDele"
                        >
                            批量删除
                        </a-button>
                    </a-space>
                </a-form-item>
            </a-col>
        </a-row>
    </a-form>
</template>
<script lang="ts" setup>
import {
    reactive,
    defineProps,
    toRefs,
    defineEmits,
    toRaw,
    ref,
    onMounted,
    nextTick,
    defineExpose
} from 'vue';
import { Form } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';
const emits = defineEmits(['search-change', 'search-reset', 'to-add', 'to-all-delete']);
const searchLoaded = ref<boolean>(false);
type RangeValue = [Dayjs, Dayjs];
const dates = ref<RangeValue>();
const hackValue = ref<RangeValue>();
const props = defineProps({
    options: {
        type: Object,
        default: () => {
            return {
                column: []
            };
        }
    }
});
const { options } = toRefs(props);
const hasDefaultValueColum = options.value.column.filter(
    (item: any) => item.search && item.defaultVlaue
);
const defaultValue: any = {};
if (hasDefaultValueColum.length) {
    hasDefaultValueColum.forEach((item: any) => {
        defaultValue[item.key] = item.defaultVlaue;
    });
}

// const modelRef: any = reactive({ ...defaultValue });
const modelRef = ref<any>({});
const modelRules = ref<any>(null);
const useFormObj = ref<any>({});
const useForm = Form.useForm;

const fuzzyQueryRef = ref('');
onMounted(() => {
    setSearchDefault();
    setRules();
    useFormObj.value = useForm(modelRef, reactive(modelRules.value));
    nextTick(() => {
        searchLoaded.value = true;
    });
});
type disabledDateFn = (current: Dayjs) => boolean;
const disabledDateCompute = (disabledDate: disabledDateFn, current: Dayjs, disabledDays: number) => {
    let flag = false;
    if (typeof disabledDate === 'function') {
        flag = disabledDate(current);
        if (disabledDays) {
            if (!dates.value || (dates.value as any).length === 0) {
            } else {
                const tooLate = dates.value[0] && current.diff(Number(dates.value[0]), 'days') > disabledDays - 1;
                const tooEarly = dates.value[1] && dayjs(Number(dates.value[1])).diff(current, 'days') > disabledDays - 1;
                return flag || tooEarly || tooLate;
            }
        }
    }
    return flag;
}

const onOpenChange = (open: boolean) => {
  if (open) {
    dates.value = [] as any;
    hackValue.value = [] as any;
  } else {
    hackValue.value = undefined;
  }
};

const onCalendarChange = (val: RangeValue) => {
    console.log(dates.value, 'onCalendarChange');
    dates.value = val;
};
const onOk = (datesSave: RangeValue | [string, string]) => {
    console.log(datesSave, 'datesSave');
}
function searchChange() {
    useFormObj.value
        .validate()
        .then(() => {
            console.log('xxxxxxxxxxxxxxxxxx', toRaw(modelRef.value));
            emits('search-change', toRaw(modelRef.value));
        })
        .catch((err: any) => {
            console.log('error', err);
        });
}

function setRules() {
    const column = toRaw(options.value).column.filter((item: any) => {
        return item.search && item.searchRules && item.searchRules.length > 0;
    });
    const modelRulesArr = column.map((item: any) => {
        return {
            key: item.key,
            rules: item.searchRules
        };
    });
    modelRules.value = modelRulesArr.reduce((acc: any, cur: any) => {
        acc[cur.key] = cur.rules;
        return acc;
    }, {});
}

function setSearchDefault() {
    const hasDefaultValueColum = options.value.column.filter((item: any) => item.defaultVlaue);
    if (hasDefaultValueColum.length) {
        hasDefaultValueColum.forEach((item: any) => {
            modelRef.value[item.key] = item.defaultVlaue;
        });
    }
}

function searchReset() {
    for (let key in modelRef.value) {
        modelRef.value[key] = void 0;
    }
    const hasDefaultValueColum = options.value.column.filter((item: any) => item.defaultVlaue);
    if (hasDefaultValueColum.length) {
        hasDefaultValueColum.forEach((item: any) => {
            modelRef.value[item.key] = item.defaultVlaue;
        });
    }
    console.log(fuzzyQueryRef.value);
    //重置模糊查询
    options.value.column.filter((item: any) => item.type == 'fuzzyQuery').length &&
        fuzzyQueryRef.value[0]?.resetHandle();
    emits('search-reset', modelRef.value);
}

function toAdd() {
    emits('to-add');
}
function toAllDele() {
    emits('to-all-delete');
}

defineExpose({
    setSearchDefault,
    searchChange
});
</script>
<style lang="scss" scoped>
.search-form {
    margin: 8px 0 24px 0;
}
.loading-more-style {
    width: 100%;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
}
</style>
